package com.pfzy.lib.net.subscriber;

import com.pfzy.lib.net.BaseEntity;
import com.pfzy.lib.net.ServiceManager;
import com.pfzy.lib.net.exception.CCHttpException;
import com.pfzy.lib.net.exception.ExceptionHandler;
import com.pfzy.lib.sdk.log.UXLog;

import java.util.HashSet;
import java.util.Set;

public abstract class CCSubscriber<T> extends BaseSubscriber<BaseEntity<T>> {
    public static Set<Integer> sSuccessCodes = new HashSet<>();

    static {
        sSuccessCodes.add(0);
    }

    public CCSubscriber() { }

    public CCSubscriber(boolean showErrorToast) {
        super(showErrorToast);
    }

    public static void updateSuccessCode(int[] codes) {
        HashSet set = new HashSet<>();
        if (codes == null || codes.length == 0) {
            set.add(0);
        } else {
            for (int code : codes) {
                set.add(Integer.valueOf(code));
            }
        }
        sSuccessCodes = set;
    }

    @Override
    public final void onError(Throwable e) {
        CCHttpException exception = ExceptionHandler.handleHttpException(e);
        if (!onHttpOrDataRevertError(exception.mCode, exception.mMessage)) {
            onFailed(exception.mCode, exception.mMessage);
        }
        onFinish();
    }

    private void handleBiz(BaseEntity baseEntity) {
        CCHttpException bizException = ExceptionHandler.handleBizException(baseEntity);
        if (!onBizError(baseEntity)) {
            onFailed(bizException.mCode, bizException.mMessage);
        }
    }

    public boolean onBizError(BaseEntity baseEntity) {
        return false;
    }

    public boolean onHttpOrDataRevertError(int code, String message) {
        return false;
    }

    @Override
    public void onFinish() {}

    protected abstract void onCCSuccess(T t);

    @Override
    public final void onSuccess(BaseEntity<T> data) {
        try {
            if (isSuccessCode(data.code)) {
                onCCSuccess(data.data);
            } else {
                handleBiz(data);
            }
        } catch (Exception e) {
            if (ServiceManager.mDebugMode) {
//                io.reactivex.exceptions.OnErrorNotImplementedException
//                io.reactivex.exceptions.CompositeException
//                io.reactivex.exceptions.MissingBackpressureException
//                io.reactivex.exceptions.ProtocolViolationException
//                io.reactivex.exceptions.UndeliverableException
//                io.reactivex.exceptions.Exceptions.propagate()
//                Exceptions.throwIfFatal();
//                throw new OnErrorFailedException("onSuccess()方法中出现异常，请检查！", e);
                UXLog.d("CCSubscriber",e.getMessage());
            }
            throw e;
        }
    }

    private boolean isSuccessCode(int code) {
        return sSuccessCodes.contains(Integer.valueOf(code));
    }
}
